package com.editor.controller;

import com.alibaba.fastjson.JSON;
import com.editor.utils.GlobalConst;
import com.editor.utils.MarkdownImg;

import com.editor.utils.MarkdownUtil;
import com.youbenzi.md2.util.MDUtil;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.stream.FileImageInputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.*;
import java.util.Collection;
import java.util.UUID;

/**
 * @author 19417
 */
@Controller
public class MarkdownController {


    @RequestMapping("/md")

    public String markdownhtml() {
        return "markdown";
    }

    @PostMapping("/imageUpload")
    public void imageUpload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        MarkdownImg res = new MarkdownImg();

        //获取上传的文件集合
        Collection<Part> parts = request.getParts();
        //上传单个文件
        if (parts != null && parts.size() == 1) {
            //通过表单file控件(<input type="file" name="file">)的名字直接获取Part对象
            Part part = request.getPart("editormd-image-file");
            //获取请求头
            String header = part.getHeader("content-disposition");
            String imgFileName = getFileName(header);
            String paht = GlobalConst.BASE_PATH + GlobalConst.IMG_FOLDER;
            String url = GlobalConst.BASE_PATH + GlobalConst.IMG_FOLDER + imgFileName;

            File file = new File(url);
            File file1 = new File(paht);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            //把文件写到指定路径
            part.write(url);

            res.setSuccess(1);
            res.setMessage("上传成功");
            StringBuffer requestURL = request.getRequestURL();
            String substring = requestURL.substring(0, requestURL.lastIndexOf("/"));
            res.setUrl(substring + "/imageShow?imgFileName=" + imgFileName);
        } else {
            res.setSuccess(0);
            res.setMessage("上传失败");
        }

        //必须有
        PrintWriter out = response.getWriter();
        out.println(JSON.toJSONString(res));
        out.flush();
        out.close();

    }


    /**
     * 图片回显
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/imageShow")
    public void imageShow(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        OutputStream out = response.getOutputStream();
        String imgFileName = request.getParameter("imgFileName");
        String imgFileNameWithPath = GlobalConst.BASE_PATH + GlobalConst.IMG_FOLDER + imgFileName;
        try (FileImageInputStream input = new FileImageInputStream(new File(imgFileNameWithPath));
             ByteArrayOutputStream output = new ByteArrayOutputStream();) {
            byte[] buf = new byte[1024];
            int len = -1;
            while ((len = input.read(buf)) != -1) {
                output.write(buf, 0, len);
            }
            byte[] data = output.toByteArray();
            out.write(data);
            out.flush();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 显示文件
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/showFile")
    public void fileShow(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        OutputStream out = response.getOutputStream();
        String imgFileName = request.getParameter("myfile");
        String imgFileNameWithPath = GlobalConst.BASE_PATH + imgFileName;
        try (FileImageInputStream input = new FileImageInputStream(new File(imgFileNameWithPath));
             ByteArrayOutputStream output = new ByteArrayOutputStream();) {
            byte[] buf = new byte[1024];
            int len = -1;
            while ((len = input.read(buf)) != -1) {
                output.write(buf, 0, len);
            }
            byte[] data = output.toByteArray();
            out.write(data);
            out.flush();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }

    @PostMapping("/saveMarkdown")
    @ResponseBody
    public String saveMarkdown(@RequestParam("value") String value, HttpServletRequest request) {

        String html = MarkdownUtil.markdownToHtmlExtensions(value);

        StringBuilder sb = new StringBuilder();
        sb.append("<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>文章详情</title>\n" +
                "    <link rel=\"stylesheet\" href=\"prims/prism.css\">\n" +
                "    <link rel=\"stylesheet\" href=\"prims/typo.css\">\n" +
                "</head>\n" +
                "<body>\n" +
                "<div id=\"wrapper\" class=\"typo typo-selection\">");

         sb.append(html);

        sb.append("</div>\n" +
                "<script type=\"text/javascript\" src=\"prims/prism.js\"></script>\n" +
                "</body>\n" +
                "</html>");
        System.out.println(sb.toString());
        try {
            String uuid = UUID.randomUUID().toString().substring(0, 9);
            String savePath = GlobalConst.BASE_PATH + uuid + ".html";
            File file = new File(savePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream outputStream = new FileOutputStream(savePath);
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            bufferedWriter.write(sb.toString());
            bufferedWriter.newLine();// 换行
            bufferedWriter.flush();
            bufferedWriter.close();

            return uuid + ".html";
        } catch (IOException e) {

            return null;

        }

    }

    /**
     * 根据请求头解析出文件名
     *
     * @param header 请求头
     * @return 文件名
     */
    public String getFileName(String header) {
        String[] temp = header.split(";")[2].split("=");
        //获取文件名，兼容各种浏览器的写法
        String fileName = temp[1].substring(temp[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        return UUID.randomUUID().toString().replaceAll("-", "").substring(3, 9) + suffix;
    }


}
